#include "apue.h"
#include <sys/ioctl.h>
#include <errno.h>

static void sig_pipe(int);
int main(void) {
    int n, fd1[2], fd2[2];
    pid_t pid;
    FILE *pt1, *pt2;
    char line[MAXLINE];

    if (signal(SIGPIPE, sig_pipe) == SIG_ERR)
        err_sys("signal error");
    if (pipe(fd1) < 0 || pipe(fd2) < 0)
        err_sys("pipe error");

    if ((pid= fork()) < 0)
        err_sys("fork error");
    if (pid > 0) {
        close(fd1[0]);
        close(fd2[1]);

        if((pt1= fdopen(fd1[1], "w")) == NULL || (pt2= fdopen(fd2[0], "r")) == NULL)
            err_sys("fdopen error");

        setbuf(pt2, NULL);
        while (fgets(line, MAXLINE, stdin) != NULL) {
            n= strlen(line);
            //if (write(fd1[1], line, n) != n)
            //    err_sys("write error to pipe");

            if (fwrite(line, sizeof(char), n, pt1) != n)
                err_sys("write error to pipe");
            fflush(pt1);

            // ioctl(fileno(pt2), FIONREAD, &m);
            // printf("pipe current bytes is :%d\n", m);

            // if ((n= fread(line, sizeof(char), MAXLINE, pt2)) < 0)
            if (fgets(line, MAXLINE, pt2) == NULL) {
                if (feof(pt2)) {
                     err_msg("child closed pipe");
                    break;
                } else {
                    err_sys("fgets error");
                }
            }

            // line[n]= 0; # this line should remove if use fgets above
            if (fputs(line, stdout) == EOF)
                err_sys("fputs error");
        }
        if (ferror(stdin))
            err_sys("fgets error on stdin");
        exit(0);

    } else {
        close(fd1[1]);
        close(fd2[0]);
        if (fd1[0] != STDIN_FILENO) {
            if (dup2(fd1[0], STDIN_FILENO) != STDIN_FILENO)
                err_sys("dup2 error to stdin");
            close(fd1[0]);
        }
        if (fd2[1] != STDOUT_FILENO) {
            if (dup2(fd2[1], STDOUT_FILENO) != STDOUT_FILENO)
                err_sys("dup2 error to stdout");
            close(fd2[1]);
        }
        if (execl("./plus2", "plus2", NULL) < 0)
            err_sys("excel error");
    }
    exit(0);
}

static void sig_pipe(int signo) {
    printf("SIGPIPE caught\n");
    exit(1);
}

